package itheima.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class ServerReaderThread extends Thread {
    private Socket socket;
    public ServerReaderThread(Socket socket) {
        this.socket = socket;
    }
    public void updateSocketMap() {
        // 更新全部客户端的在线列表
        for (Socket socket : Server.socketMap.keySet()) {
            try {
                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                // 1 代表在线人数列表消息，2 代表群聊消息
                dos.writeInt(1);
                dos.writeInt(Server.socketMap.size());
                for (String username : Server.socketMap.values()) {
                    dos.writeUTF(username);
                }
                dos.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private void callAll(String message) {
        // 群聊信息 姓名 时间\r\n消息
        StringBuilder sb = new StringBuilder();
        String name = Server.socketMap.get(socket);
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Constant.FORMATTER, Locale.CHINA);
        String time = formatter.format(now);
        sb.append(name).append("：").append(time).append("\r\n").append(message).append("\r\n");
        String sendMessage = sb.toString();

        for (Socket socket : Server.socketMap.keySet()) {
            try {
                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                // 1 代表在线人数列表消息，2 代表群聊消息
                dos.writeInt(2);
                dos.writeUTF(sendMessage);
                dos.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void run() {
        DataInputStream dis = null;
        try {
            dis = new DataInputStream(socket.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        while (true) {
            try {
                // 接受消息类型定义：1.登录消息 2.群聊消息
                int type = dis.readInt();
                switch (type) {
                    case 1:
                        // 登录消息
                        String username = dis.readUTF();
                        System.out.println("****************************");
                        System.out.println("用户“" + username + "”登录了");
                        System.out.println("****************************");
                        Server.socketMap.put(socket, username);
                        // 更新所有客户端的在线列表
                        updateSocketMap();
                        break;
                    case 2:
                        // 群聊消息
                        String message = dis.readUTF();
                        callAll(message);
                        break;
                    default:
                        break;
                }
            }
            catch (EOFException e) {
                continue;
            }
            catch (Exception e) {
                System.out.println("用户“" + Server.socketMap.get(socket) + "”断开连接");
                Server.socketMap.remove(socket);
                updateSocketMap();
                break;
            }
        }
    }
}
